import confirmorderService from '../../services/confirmorder';
import goodsService from '../../services/goods';
import util from '../../utils/util'
import router from '../../utils/router'
import authorize from '../../utils/authorize'
import detail from '../../services/detail.js'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    address: null,
    user_info: null,
    options: null,
    goods: null,
    isCreateOrder: false,
    pic: '', //图片

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    wx.hideShareMenu();
    if (options.types == 1) {
      if (!options || !options.segsid || !options.bslnid) {
        let notstr = '下单参数不全';
        if (!options) {
          notstr += 'options'
        }
        if (options && !options.segsid) {
          notstr += ' segsid'
        }
        if (options && !options.bslnid) {
          notstr += ' bslnid'
        }
        return wx.showToast({
          title: notstr,
          icon: 'none',
          duration: 5000
        })
      }
    }

    this.setData({
      address: wx.getStorageSync('address') || null,
      user_info: wx.getStorageSync('user_info') || null,
      options
    });

    // 接龙商品
    if (options.types == 1) {
      this.solitaireGoods();
    } else if (options.types == 2) {
      this.getBargainGoods()
    }


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  // 接龙商品
  solitaireGoods: function () {
    let options = this.data.options;
    let opt = {
      segsid: options.segsid,
      store_id: options.bslnid
    };
    goodsService.solitaireGoods(opt, res => {
      if (res && res.code == 1 && res.data) {
        let data = res.data;
        let sku = '';
        let arr_sku = [];
        let orig_price = '';
        let sale_price = options.sale_price;
        let sale_price_all = '';
        let org_sale_price_all = '';

        let _this = this;

        if (options.sku_str) {
          data.goodsSku.forEach((item) => {
            if (item.str_attr_val_id == options.sku_str) {
              orig_price = item.orig_price;
              if (item.img) {
                _this.setData({
                  pic: 'https:' + item.img
                })
              } else {
                _this.setData({
                  pic: 'https:' + data.goodsPic[0].url
                })
              }
            }
          });

          arr_sku = options.sku_str.split(',');

          if (arr_sku.lenth == 1) {
            // 单sku
            for (let i in data.goodsParam) {
              if (data.goodsParam[i].attr_value_id == arr_sku[0]) {
                sku += `${i}:${data.goodsParam[i][a].attr_value_name} `;
                return false;
              }
            }


          } else {
            // 双sku
            arr_sku.forEach((item) => {
              for (let i in data.goodsParam) {
                for (let a in data.goodsParam[i]) {
                  if (data.goodsParam[i][a].attr_value_id == item) {
                    sku += `${i}:${data.goodsParam[i][a].attr_value_name} `;
                  }
                }

              }
            })

          }

        } else {
          orig_price = data.goodsSku[0].orig_price;
          _this.setData({
            pic: 'https:' + data.goodsPic[0].url
          })
        }

        sale_price_all = util.floatAccMul(sale_price, options.goods_num || 1).toFixed(2);
        
        this.setData({
          goods: {
            name: data.goods.name,
            num: options.goods_num || 1,
            share_url: data.solitaire_goods.share_url,
            is_allow_return: data.goods.is_allow_return ||'',
            sku,
            orig_price,
            sale_price,
            org_sale_price_all: sale_price_all,
            sale_price_all,
          }
        });
      }

    })
  },

  // 选择收货地址
  chooseAddress: function () {
    let _this = this;

    authorize('address', (b) => {
      if (b) {
        wx.chooseAddress({
          success(res) {
            res.txt = `${res.provinceName} ${res.cityName} ${res.countyName}${res.detailInfo}`
            wx.setStorageSync('address', res);
            _this.setData({
              address: res
            });
            // cityName:"广州市"
            // countyName:"海珠区"
            // detailInfo:"新港中路397号"
            // nationalCode:"510000"
            // postalCode:"510000"
            // provinceName: "广东省"
            // telNumber :"020-81167888"
            // userName: "张三"
          },
          fail(res) { }
        });
      }
    })


  },
  // 接龙订单
  submit_jielong: function (e) {

    let data = this.data;
    let options = data.options;
    let address = data.address;
    let user_info = data.user_info;

    if (this.extAddress()) {

      this.setData({
        isCreateOrder: true
      });
      console.log(options)
      let opt = {
        bnorid: options.bnorid, //砍价id
        segsid: options.segsid, //接龙id
        goods_title: data.goods.name,
        bslnid: options.bslnid,
        goods_num: options.goods_num || 1,
        goods_list_money: this.data.goods.sale_price_all,
        address: address.txt,
        province_name: address.provinceName,
        city_name: address.cityName,
        area_name: address.countyName,
        buyer_name: address.userName,
        tel: address.telNumber,
        goods_img: this.data.pic,
        sku_str: options.sku_str,
        wechat_scene: getApp().globalData.scene,
        order_source: getApp().globalData.sharerecord
      }
      //接龙提交订单
      if (options.types == 1) {
        confirmorderService.create_solitaire_order(opt, (res) => {
          if (res && res.code == 1) {
            return this.toJielongPay(res.data);
          }

          this.setData({
            isCreateOrder: false
          });

          return wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 5000
          });
        })
      } else if (options.types == 2) {

        confirmorderService.create_bargain_order(opt, (res) => {
          console.log(res)
          if (res && res.code == 1) {
            return this.toJielongPay(res.data);
          }

          this.setData({
            isCreateOrder: false
          });

          return wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 5000
          });
        })
      }

    }
  },
  // 验证地址
  extAddress: function () {
    let address = this.data.address;
    if (!address || !address.provinceName) {
      return wx.showToast({
        title: '请设置收货地址',
        icon: 'none',
        duration: 2000
      });
      return false;
    }

    if (/西藏|新疆|内蒙|香港|澳门|台北/.test(address.provinceName)) {
      return wx.showToast({
        title: `所在地区当前无法配送`,
        icon: 'none',
        duration: 2000
      });
      return false;
    }

    return true;
  },
  // 接龙支付
  toJielongPay: function (data) {
    var _this = this;
    let user_info = this.data.user_info;
    console.log('292',data)
    let opt = {
      order_num: data.order_num,
      run_num: data.run_num,
      openid: user_info.openid,
      bsln_name: user_info.user_nickname,
    }
    //支付接龙订单
    if (this.data.options.types == 1) {
      console.log('301',opt)
      confirmorderService.pay_solitaire_order(opt, res => {
        if (res && res.code == 1) {
          let d = res.data;
          util.toPay(d, b => {
            let str = `orid=${data.orid}&run_num=${data.run_num}&store_id=${_this.data.options.bslnid}&segsid=${_this.data.options.segsid}&share_url=${encodeURIComponent(_this.data.goods.share_url)}`;
            console.log(d,b)
            if (b) {
              router.go('payhot', str, 'redirectTo');
            }else{
              // router.go('orderDetail', str, 'redirectTo');
            }
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 5000
          });
        }
        this.setData({
          isCreateOrder: false
        });

      });
      //支付砍价订单
    } else if (this.data.options.types == 2){
      confirmorderService.payOrder(opt, res => {
        if (res && res.code == 1) {
          let d = res.data;
          util.toPay(d, b => {
            let str = `orid=${data.orid}&run_num=${data.run_num}&store_id=${_this.data.options.store_id}&bnorid=${_this.data.options.bnorid}&share_url=${encodeURIComponent(_this.data.pic)}`;
            if (b) {
              router.go('payhot', str, 'redirectTo');
            }else{
              router.go('orderDetail', str, 'redirectTo');
            }
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 5000
          });
        }
        this.setData({
          isCreateOrder: false
        });

      });
    }


  },

  getPriceall(num) { //得到最终金额 1为减去红包+邻钱 2为减去红包+优惠券 3只选择了红包
    var all = this.data.goods.org_sale_price_all;
    var _this = this;
    if (num == 1) {
      var maybe = util.floatAccMul(all, 0.7)
      if (this.data.bybslt_money >= all) { //红包金额大于商品金额 禁止选中邻钱
        this.setData({
          'goods.sale_price_all': 0.01,
          lin_use_money: 0,
          // checklins: true
        })
      } else { //再判断同时使用红包和邻钱的时候 红包金额大于等于商品总额的70% 计算邻钱
        if (this.data.bybslt_money >= maybe) {
          var lin = util.floatAccSub(all, this.data.bybslt_money);
          var money = util.floatAccSub(lin, 0.01);
          var lins = util.floatAccSub(lin, money);
          this.setData({
            lin_use_money: money,
            'goods.sale_price_all': lins
          })
        } else {
          let price = util.floatAccSub(all, this.data.lin_use_money)
          let money = util.floatAccSub(price, this.data.bybslt_money)
          this.setData({
            'goods.sale_price_all': money
          })
        }
      }

    } else if (num == 2) { //选择为红包➕优惠券的组合 应付金额
      let price = util.floatAccSub(all, this.data.cardmoney)
      let money = util.floatAccSub(price, this.data.bybslt_money)
      if (money <= 0) {
        this.setData({
          'goods.sale_price_all': 0.01
        })
      } else {
        this.setData({
          'goods.sale_price_all': Number(money).toFixed(2)
        })
      }
    } else if (num == 3) {
      var money = util.floatAccSub(all, this.data.bybslt_money);
      if (money <= 0) {
        _this.setData({
          'goods.sale_price_all': 0.01
        })
      } else {
        _this.setData({
          'goods.sale_price_all': money
        })
      }
    }


  },
  //砍价商品详情
  getBargainGoods() {
    let _this = this;
    let params = {
      bnorid: this.data.options.bnorid
    }
    detail.getbargainorderdetail(params, res => {
      if (res.code == 1) {
        let sale_price = res.data.orders.goods_list_money;
        let difference = util.floatAccSub(sale_price, _this.data.options.difference);
        _this.setData({
          goods: {
            name: res.data.orders.goods_title,
            num: _this.data.options.goods_num || 1,
            sale_price: sale_price,
            difference: difference,
            sale_price_all: _this.data.options.difference,
            is_allow_return: res.data.orders.is_allow_return
          },
          pic: 'https:' + res.data.orders.goods_pic
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})